var express = require('express');
var router = express.Router();

const pool = require('../pool.js')

// 用户登录路由
router.get("/login", (req, res) => {
    let sql1 = "SELECT userid FROM demo_user WHERE account = ? AND pwd = ?;"
    pool.query(sql1, [req.query.account, req.query.pwd], (err, result) => {
        if (err) throw err
        if (result.length > 0) {
            res.send({
                code: "1",
                msg: "登陆成功",
                userid: result[0].userid
            })
            console.log(`${req.query.account}登陆成功,时间:  ${new Date().toLocaleString()}`)
        } else {
            res.send({
                code: "0",
                msg: "账号或密码错误"
            })
            console.log(`${req.query.account}登陆失败,时间:  ${new Date().toLocaleString()}`)
        }
    })
})

// 获取用户详细信息路由
router.get("/getDetail", (req, res) => {
    let sql = "select username,QQ,email,phone,sex,address,avatar,usertyp from demo_user where userid = ?;"
    pool.query(sql, [req.query.userid], (err, result) => {
        if (err) throw err
        res.send(result)
    })
    console.log(`id为 ${req.query.userid} 的用户查询了用户详细信息,时间:  ${new Date().toLocaleString()}`)
})

// 修改用户详细信息路由
router.get("/updateDetail", (req, res) => {
    let sql = "UPDATE demo_user SET username = ? , QQ = ? , phone = ? , sex = ? , address = ? , usertyp = ? where userid = ?;"
    pool.query(sql, [req.query.username, req.query.QQ, req.query.phone, req.query.sex, req.query.address, req.query.usertyp, req.query.userid], (err, result) => {
        if (err) throw err
        if (result.affectedRows == 1) {
            res.send({
                code: "1",
                msg: "修改成功"
            })
            console.log(`id为 ${req.query.userid} 的用户修改了用户详细信息,时间:  ${new Date().toLocaleString()}`)
        } else {
            res.send({
                code: "0",
                msg: "修改失败"
            })
        }
    })
})

// 修改密码路由
router.get("/updatePwd", (req, res) => {
    console.log(req.query)
    var sql = "select * from demo_user where userid = ? and pwd = ? ;"
    pool.query(sql, [req.query.userid, req.query.oldPwd], (err, result) => {
        if (err) throw err
        if (result.length == 0) {
            res.send({
                code: "0",
                msg: "原密码不正确"
            })
        } else if (result.length == 1) {
            var sql1 = "update demo_user set pwd = ? where userid = ? and pwd = ? ;"
            pool.query(sql1, [req.query.newPwd, req.query.userid, req.query.oldPwd], (err1, result1) => {
                if (err) throw err1
                if (result1.affectedRows == 1) {
                    res.send({
                        code: "1",
                        msg: "修改成功,请重新登陆!"
                    })
                } else {
                    res.send({
                        code: "0",
                        msg: "修改失败,请联系管理员"
                    })
                }
            })
        }
    })
})

module.exports = router;